package com.btl.service.ai.support.memory;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

/**
 * RedisChatMemoryStore
 */
@Slf4j
public class RedisChatMemoryStore implements ChatMemoryStore {

    private final RedisTemplate<String, String> redisTemplate;
    private static final String KEY_PREFIX = "ai:chat:memory:";

    public RedisChatMemoryStore(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    private String buildKey(Object memoryId) {
        return KEY_PREFIX + memoryId;
    }

    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String key = buildKey(memoryId);
        String json = redisTemplate.opsForValue()
                .get(key);
        log.debug("getMessages: key={}, json={}", key, json);
        if (json == null || json.isBlank()) {
            return List.of();
        }
        try {
            return ChatMessageDeserializer.messagesFromJson(json);
        } catch (Exception e) {
            log.error("Failed to deserialize chat messages from Redis for key: {}", key, e);
            return List.of();
        }
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> chatMessages) {
        String key = buildKey(memoryId);
        String json = ChatMessageSerializer.messagesToJson(chatMessages);
        log.debug("updateMessages: key={}, messageCount={}", key, chatMessages.size());
        redisTemplate.opsForValue()
                .set(key, json);
    }

    @Override
    public void deleteMessages(Object memoryId) {
        String key = buildKey(memoryId);
        log.debug("deleteMessages: key={}", key);
        redisTemplate.delete(key);
    }
}
